package com.cljz.makepassenger.ui.holder;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cljz.makepassenger.base.App;
import com.cljz.makepassenger.R;
import com.cljz.makepassenger.base.Constant;
import com.cljz.makepassenger.model.net.bean.InviteListBean;
import com.cljz.makepassenger.ui.activity.InvitationLetterActivity;
import com.cljz.makepassenger.ui.adapter.InviteListAdapter;
import com.cljz.makepassenger.utils.L;
import com.cljz.makepassenger.utils.T;
import com.clzj.makepassenger.bean.UserInfo;
import com.clzj.makepassenger.dao.UserInfoDao;
import com.jakewharton.rxbinding.view.RxView;
import com.squareup.picasso.Picasso;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.router.Router;
import de.greenrobot.dao.query.Query;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.functions.Action1;


/**
 * Created by apple on 2017/4/6.
 */

public class InviteListHolder extends RecyclerView.ViewHolder implements View.OnTouchListener, GestureDetector.OnGestureListener {

    private final RecyclerView.Adapter adapter;
    @BindView(R.id.iv_share_from)
    ImageView ivShareFrom;
    @BindView(R.id.tv_share_title)
    TextView tvShareTitle;
    @BindView(R.id.iv_share_wechat)
    ImageView ivShareWechat;
    @BindView(R.id.iv_share_friends)
    ImageView ivShareFriends;
    @BindView(R.id.iv_share_qq)
    ImageView ivShareQq;
    @BindView(R.id.iv_share_qzone)
    ImageView ivShareQzone;
    @BindView(R.id.backView)
    LinearLayout backView;
    @BindView(R.id.iv_from)
    ImageView ivFrom;
    @BindView(R.id.tv_invite_title)
    TextView tvInviterTitle;
    @BindView(R.id.civ_head)
    CircleImageView civHead;
    @BindView(R.id.tv_invite_time)
    TextView tvInviterTime;
    @BindView(R.id.tv_invite_place)
    TextView tvInviterPlace;
    @BindView(R.id.tv_invite_member)
    TextView tvInviterMember;
    @BindView(R.id.ll_invite_describe)
    LinearLayout llInviterDescribe;
    @BindView(R.id.frontView)
    LinearLayout frontView;
    @BindView(R.id.itemCardView)
    FrameLayout itemCardView;
    @BindView(R.id.iv_tag)
    ImageView ivTag;

    private InviteListBean.DataBean data;
    private GestureDetector mGestureDetector;


    private AnimatorSet mRightOutSet; // 右出动画
    private AnimatorSet mLeftInSet; // 左入动画
    private AnimatorSet mRightInSet;
    private AnimatorSet mLiftOutSet;
    private List<InviteListBean.DataBean> inviterList;
    private int position;
    private int type;

    public InviteListHolder(View itemView, RecyclerView.Adapter adapter) {
        super(itemView);
        ButterKnife.bind(this, itemView);
        L.e(itemView.getClass().getSimpleName());
        itemView.setOnTouchListener(this);
        mGestureDetector = new GestureDetector(this);
        this.adapter = adapter;
    }

//    @Override
//    public void onItemSelected() {
//
//    }
//
//    @Override
//    public void onItemClear() {
//
//    }

    public void setData(List<InviteListBean.DataBean> inviterList, int position) {
        this.inviterList = inviterList;
        this.position = position;
        data = inviterList.get(position);

        setAnimators();
        setCameraDistance(frontView, backView);
        if (!data.getIs_turn() && frontView.getVisibility() == View.GONE && backView.getVisibility() == View.VISIBLE) {
            //right
            mLiftOutSet.setTarget(backView);
            mRightInSet.setTarget(frontView);
            mRightInSet.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animator) {
                    frontView.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animator animator) {
                    backView.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationCancel(Animator animator) {

                }

                @Override
                public void onAnimationRepeat(Animator animator) {

                }
            });
            mLiftOutSet.start();
            mRightInSet.start();
        } else if (data.getIs_turn() && frontView.getVisibility() == View.VISIBLE && backView.getVisibility() == View.GONE) {
            //left
            mRightOutSet.setTarget(frontView);
            mLeftInSet.setTarget(backView);
            mRightOutSet.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animator) {
                    backView.setVisibility(View.VISIBLE);
                }

                @Override
                public void onAnimationEnd(Animator animator) {
                    frontView.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationCancel(Animator animator) {

                }

                @Override
                public void onAnimationRepeat(Animator animator) {

                }
            });
            mRightOutSet.start();
            mLeftInSet.start();
        }

        setViewData();

    }

    private void setViewData() {
        if ("1".equals(data.getIs_activity())) {
//            type = InvitationLetterActivity.ACTIVITY;
            ivTag.setVisibility(View.VISIBLE);
        } else {
            ivTag.setVisibility(View.GONE);

        }
        type = InvitationLetterActivity.INVITE;
        tvInviterTitle.setText(data.getTitle());
        tvInviterTime.setText(data.getDate() + " " + data.getWeek() + " " + data.getTime());
        tvInviterPlace.setText(data.getAddress());
        tvInviterMember.setText(data.getNumber_join() + "人");
        Picasso.with(App.getInstance()).load(data.getUser_logo()).error(R.mipmap.touxiang).placeholder(R.mipmap.touxiang).into(civHead);
        if (data.getIs_invite().equals("1")) {
            ivFrom.setBackgroundDrawable(App.getInstance().getResources().getDrawable(R.mipmap.biaoqian_yaoqing));
            ivShareFrom.setBackgroundDrawable(App.getInstance().getResources().getDrawable(R.mipmap.biaoqian_yaoqing));

        } else {
            ivFrom.setBackgroundDrawable(App.getInstance().getResources().getDrawable(R.mipmap.biaoqian_shouyao));
            ivShareFrom.setBackgroundDrawable(App.getInstance().getResources().getDrawable(R.mipmap.biaoqian_shouyao));

        }
//        frontView.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                T.getInstance().showShort("frontView");
//                return_1 false;
//            }
//        });
        setListener();
    }

    private void setListener() {

        RxView.clicks(ivShareQq)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        setShare(data, SHARE_MEDIA.QQ);
                    }
                });
        RxView.clicks(ivShareQzone)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        setShare(data, SHARE_MEDIA.QZONE);
                    }
                });
        RxView.clicks(ivShareWechat).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                setShare(data, SHARE_MEDIA.WEIXIN);
            }
        });
        RxView.clicks(ivShareFriends).subscribe(new Action1<Void>() {
            @Override
            public void call(Void aVoid) {
                setShare(data, SHARE_MEDIA.WEIXIN_CIRCLE);
            }
        });
//        RxView.clicks(itemView).subscribe(new Action1<Void>() {
//            @Override
//            public void call(Void aVoid) {
//                Router.newIntent((Activity) App.getInstance()).putString("id", data.getId()).putInt("type", 1).to(InvitationLetterActivity.class).launch();
//            }
//        });
    }

    private void setShare(InviteListBean.DataBean data, SHARE_MEDIA shareMedia) {
        String token = SharedPref.getInstance(App.getInstance()).getString(Constant.TOKEN, "");
        Query<UserInfo> query = ((App) App.instance).getDaoSession().getUserInfoDao().queryBuilder()
                .where(UserInfoDao.Properties.Token.eq(token))
                .build();
        try {
            UMWeb shareWeb = new UMWeb(data.getShare_url());
            shareWeb.setTitle("1".equals(data.getIs_activity()) ? data.getTitle2() : data.getTitle());
            shareWeb.setDescription("1Q-超好用的邀请工具");
            shareWeb.setThumb(new UMImage(App.getInstance(), query.list().get(0).getUser_logo()));
            new ShareAction((Activity) App.getInstance()).setPlatform(shareMedia).setCallback(new ShareCallback())
//                    .withTitle(data.getUser_nickname() + "通过1Q给你发起了邀请")
//                    .withText(data.getTitle())
//                    .withTargetUrl(data.getShare_url())
                    .withMedia(shareWeb)
                    .share();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public InviteListBean.DataBean getData() {
        return data;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        //手势触摸
        mGestureDetector.onTouchEvent(motionEvent);
        return true;
    }


    //最小化动距离
    private static final float FLING_MIN_DISTANCE = Kits.Dimens.dpToPx(App.getInstance(),20);
    //垂直最小滑动距离
    private static final float FLING_MIN_VELOCITY =  Kits.Dimens.dpToPx(App.getInstance(),15);

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        if (frontView.getVisibility() == View.VISIBLE) {
            Router.newIntent((Activity) App.getInstance()).putString("id", data.getInvite_id()).putInt("type", type).to(InvitationLetterActivity.class).launch();
        }
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float v1) {
        //左滑动显示
        if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            if (!data.getIs_turn()) {
                int count = inviterList.size();
                for (int i = 0; i < count; i++) {
                    if (i == position) {
                        inviterList.get(i).setIs_turn(true);
                    } else {
                        inviterList.get(i).setIs_turn(false);
                    }
                }
            }
            //右滑动隐藏
        } else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE && Math.abs(velocityX) > FLING_MIN_VELOCITY) {
            if (!data.getIs_turn()) {
//                if ("1".equals(data.getIs_invite())) {
//                    Router.newIntent((Activity) App.getInstance()).putSerializable("data", data).to(ChangeTimeActivity.class).anim(R.anim.in_from_left, R.anim.out_to_right).launch();
//                }
            } else if (data.getIs_turn()) {
                data.setIs_turn(false);
            }
        }
        ((InviteListAdapter) adapter).setData(inviterList);
        adapter.notifyDataSetChanged();
        return false;
    }


    private static class ShareCallback implements UMShareListener {

        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA share_media) {
            shareResult(share_media, "分享成功");
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            shareResult(share_media, "分享失败");

        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            shareResult(share_media, "取消分享");
        }

        private void shareResult(SHARE_MEDIA platform, String msg) {
            if (SHARE_MEDIA.QQ.equals(platform)) {
                T.getInstance().showShort(" QQ " + msg);
            } else if (SHARE_MEDIA.QZONE.equals(platform)) {
                T.getInstance().showShort(" QQ空间 " + msg);
            } else if (SHARE_MEDIA.WEIXIN.equals(platform)) {
                T.getInstance().showShort(" 微信 " + msg);
            } else if (SHARE_MEDIA.WEIXIN_CIRCLE.equals(platform)) {
                T.getInstance().showShort(" 微信朋友圈 " + msg);
            }
        }
    }


    private void setAnimators() {
        mRightOutSet = (AnimatorSet) AnimatorInflater.loadAnimator(App.getInstance(), R.animator.anim_front_out);
        mLeftInSet = (AnimatorSet) AnimatorInflater.loadAnimator(App.getInstance(), R.animator.anim_front_in);
        mRightInSet = (AnimatorSet) AnimatorInflater.loadAnimator(App.getInstance(), R.animator.anim_back_in);
        mLiftOutSet = (AnimatorSet) AnimatorInflater.loadAnimator(App.getInstance(), R.animator.anim_back_out);

    }

    private void setCameraDistance(View frontView, View backView) {
        int distance = 16000;
        float scale = App.getInstance().getResources().getDisplayMetrics().density * distance;
        if (null != frontView && null != backView) {
            frontView.setCameraDistance(scale);
            backView.setCameraDistance(scale);
        }
    }
}
